#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode *next;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class goodLeafPairs {
public:
    int countPairs(TreeNode* root, int distance) {
        int ans = 0;
        dfs(root, distance, ans);
        return ans;
    }

    vector<int> dfs(TreeNode* root, int distance, int& ans) {
        // depth[i]记录到root的距离为i的节点个数，由于是递归实现，先deep后back，因此得到的一定是最短路
        vector<int> depths(distance + 1, 0);
        if (!root->left && !root->right) {
            depths[0] = 1;
            return depths;
        }

        vector<int> leftDepths(distance + 1, 0), rightDepths(distance + 1, 0);
        if (root->left)
            leftDepths = dfs(root->left, distance, ans);
        if (root->right)
            rightDepths = dfs(root->right, distance, ans);
        
        for (int i = 0; i < distance; i++) {
            depths[i + 1] += leftDepths[i];
            depths[i + 1] += rightDepths[i];
        }

        for (int i = 0; i <= distance; i++) 
            for (int j = 0; i + j + 2 <= distance; j++)
                ans += (leftDepths[i] * rightDepths[j]);

        return depths;
    }
};